package com.example.work3

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.PersistableBundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import kotlin.jvm.java
import kotlin.time.Duration.Companion.seconds


class Activity5 : AppCompatActivity() {

    var seconds = 0
    var running = false
    var wasrunning = false

        override fun onCreate(savedInstanceState: Bundle?)
        {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_5)
            Log.d("Life cycle", "onCreate")
            enableEdgeToEdge()

            if (savedInstanceState != null) {
                seconds = savedInstanceState.getInt("seconds")
                running = savedInstanceState.getBoolean("running")
                wasrunning = savedInstanceState.getBoolean("wasrunning")
            }


            runTimer()

            val btnStart = findViewById<Button>(R.id.start)
            btnStart.setOnClickListener {
                //start timer
                running = true
            }
            val btnStop = findViewById<Button>(R.id.stop)
            btnStop.setOnClickListener {
                //stop timer
                running = false
            }
            val btnReset = findViewById<Button>(R.id.restart)
            btnReset.setOnClickListener {
                //reset timer
                seconds = 0
                running = false
            }
        }



        fun runTimer()
        {
            val handler = Handler()
            val runnable = object : Runnable {
                override fun run(){
                    val hours = seconds / 3600
                    val minutes = (seconds % 3600) / 60
                    var seconds = seconds % 60

                    val time = String.format("%d:%02d:%02d", hours, minutes, seconds)
                    findViewById<TextView>(R.id.tv_time).text = time
                    if (running) {
                        seconds++
                    }
                    handler.postDelayed(this, 1000)
                }
            }
            handler.post(runnable)
        }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("seconds", seconds)
        outState.putBoolean("running", running)
        outState.putBoolean("wasrunning", wasrunning)
    }
}